<template>
    <div class="grid" @wheel="handleScale" :style="{transform: `scale(${scale})`}">
        <canvas ref="canvas" :width="canvasSize" :height="canvasSize" style="border: 1px solid black"></canvas>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref,  shallowRef, type ShallowRef } from "vue";
import { generateColorStep, generateRandomColors } from '@/utils';
import { useGridStore } from '@/stores';
import { watch } from "vue";
//50*50的shallRef数组，每个元素是一个对象，包含color、dis、value三个属性
const squares: ShallowRef<{ color: string, dis: number, value: number }[][]> = shallowRef(Array.from({ length: 50 }));
for (let i = 0; i < 50; ++i) {
    squares.value[i] = new Array(50).fill({}).map((_, idx) => ({ color: '', dis: 0, value: Math.round(Math.random() * 100) }));
}

const colorEnds = generateRandomColors(4);
const colorsLeft = generateColorStep(colorEnds[0], colorEnds[1], 50);
const colorsRight = generateColorStep(colorEnds[2], colorEnds[3], 50);


//初始化一个canvas实例
const canvas = ref<HTMLCanvasElement | null>(null);
const canvasSize = 800;
const rows = 50;
const scale = ref(1);
const handleScale = (e: WheelEvent) => {
    if (e.deltaY > 0) {
        scale.value -= 0.1;
    } else {
        scale.value += 0.1;
    }
    scale.value = Math.max(0.1, Math.min(scale.value, 3));
}

const draw= (canvas: HTMLCanvasElement) => {
    const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
    const gridSize = canvasSize / rows;
    for (let i = 0; i < rows; i++) {
        const curColors = generateColorStep(colorsLeft[i], colorsRight[i], 50);
        for (let j = 0; j < rows; j++) {
            ctx.fillStyle = curColors[j];
            ctx.fillRect(j * gridSize, i * gridSize, gridSize, gridSize);
            //当前square的value
            const value = squares.value[i][j].value;
            //绘制value的文本
            ctx.fillStyle = '#fff';
            ctx.font = '8px Arial';
            ctx.fillText(value.toString(), j * gridSize + 5, i * gridSize + 15);
        }
    }
}

const gridStore = useGridStore();

onMounted(() => {
    if (canvas.value) {
        draw(canvas.value);
    }
});

watch(
() => gridStore.getRoomInfo, 
(newVal) => {
    console.log(`roomInfo changed: ${newVal}`);
}
);

//gridStore.$subscribe((mutation,state) => {
//    //打印 shard 和 roomName
//    console.log(`shard: ${state.shard}, roomName: ${state.roomName}`);
//});
</script>

<style>
.grid {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
